package org.example.fileswalk;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FilesWalkExample2 {
    public static void main(String[] args) throws Exception {
        Path path = Paths.get("F:\\迅雷下载");
        /*List<Path> result = findByFileExtension(path,".mp4");
        System.err.println(JSONObject.toJSONString(result,true));*/
        /*List<Path> result1 = findByFileName(path,"JetBrainsMono-Bold.ttf");
        System.err.println(JSONObject.toJSONString(result1,true));*/
        long fileSize = 1024 * 1024 * 1000;
        List<Path> result2 = findByFileSize(path,fileSize);
        System.err.println(JSONObject.toJSONString(result2,true));
    }

    static List<Path> findByFileExtension(Path path, String fileExtension) throws Exception {
        List<Path> result = null;
        if (!Files.isDirectory(path)) {
            throw new Exception("Path must be a directory");
        }
        try (Stream<Path> pathStream = Files.walk(path)) {
            result = pathStream.filter(p -> p.getFileName().toString().endsWith(fileExtension))
                    .collect(Collectors.toList());
        }
        return result;
    }

    static List<Path> findByFileName(Path path,String fileName) throws Exception {
        List<Path> result = null;
        if (!Files.isDirectory(path)) {
            throw new Exception("Path must be a directory");
        }
        try (Stream<Path> pathStream = Files.walk(path)) {
            result = pathStream.filter(Files::isReadable)
                    .filter(Files::isRegularFile)
                    .filter(p -> p.getFileName().toString().equalsIgnoreCase(fileName))
                    .collect(Collectors.toList());
        }
        return result;
    }

    static List<Path> findByFileSize(Path path,long fileSize) throws Exception {
        List<Path> result = null;
        if (!Files.isDirectory(path)) {
            throw new Exception("Path must be a directory");
        }
        try (Stream<Path> pathStream = Files.walk(path)) {
            result = pathStream.filter(Files::isReadable)
                    .filter(Files::isRegularFile)
                    .filter(p -> !Files.isDirectory(p))
                    .filter(p -> {
                        try {
                            return Files.size(p) >= fileSize;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return false;
                    })
                    .collect(Collectors.toList());
        }
        return result;
    }
}
